package cc.rengu.igas.route.common.util;

import cc.rengu.oltp.utility.util.StringUtil;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * 获取IPv4地址，过滤127.0.0.1
 *
 * @author xlz
 * copyed from 王成
 * @version 1.0
 * @date 20200414
 */
public class IPv4Util {

    public static String ipv4Address;

    static {
        Enumeration<?> allNetInterfaces = null;
        ipv4Address = "127.0.0.1";
        try {
            allNetInterfaces = NetworkInterface.getNetworkInterfaces();

            InetAddress ip = null;

            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                Enumeration<?> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = (InetAddress) addresses.nextElement();
                    if (ip instanceof Inet4Address && !ip.isLoopbackAddress()) {
                        ipv4Address = ip.getHostAddress();
                    }
                }
            }

        } catch (SocketException e) {

            System.exit(-1);
        }
    }

    /**
     * Fetch local host's IPv4 address.
     *
     * @param - null.
     * @return - local host's IPv4 address.
     */
    public static String fetchLocalHostIpv4Address() throws Exception {

        if (!StringUtil.isEmptyOrNull(ipv4Address)) {
            return ipv4Address;
        }
        Enumeration<?> allNetInterfaces = null;
        ipv4Address = "127.0.0.1";
        try {
            allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                Enumeration<?> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = (InetAddress) addresses.nextElement();
                    if (ip instanceof Inet4Address && !ip.isLoopbackAddress()) {
                        ipv4Address = ip.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            throw e;
        }
        return ipv4Address;
    }
}
